package com.d16_Socket_Homework.homework5;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

class ClientDemo5_TCP {
    public static void main(String[] args) throws IOException {
        //键盘录入
        Scanner sc = new Scanner(System.in);
        //创建发送端Socket对象
        Socket socket = new Socket("127.0.0.1",1111);
        File file = getFile();
        //缓冲输入流读取文件
        BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(file));
        //缓冲输出流写入文件
        BufferedOutputStream bos = new BufferedOutputStream(
                socket.getOutputStream());
        int b;
        while ((b=bis.read())!=-1){
            bos.write(b);
        }
        bos.flush();//刷新流
        socket.shutdownOutput();//结束输出流
        //接收服务器的回复
        BufferedReader br = new BufferedReader(
                new InputStreamReader(socket.getInputStream())
        );
        String line;
        while ((line=br.readLine())!=null){
            System.out.println(line);
        }
        //释放资源
        bis.close();
        socket.close();
    }
    private static File getFile() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个JPG格式图片文件的路径：");
        while (true) {
            File file = new File(sc.nextLine());
            if (!file.exists()) {
                System.out.println("该文件路径不存在，请重新输入：");
            } else if (file.isDirectory()) {
                System.out.println("您输入的是一个文件夹路径，请重新输入：");
            } else if (file.getName().endsWith(".jpg") || file.getName().endsWith(".JPG")) {
                return file;
            } else {
                System.out.println("您输入文件格式有误，请重新输入");
            }
        }
    }
}
